package com.wht.media.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.aizuda.zlm4j.structure.MK_MEDIA_SOURCE;
import com.wht.media.common.R;
import com.wht.media.config.MediaServerConfig;
import com.wht.media.model.Transcode;
import com.wht.media.model.constants.MediaServerConstants;
import com.wht.media.model.param.TranscodeParam;
import com.wht.media.service.ITranscodeService;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.util.RunUtil;

import java.util.HashMap;
import java.util.Map;

import static com.wht.media.context.MediaServerContext.ZLM_API;


@Slf4j
@Component
public class TranscodeServiceImpl implements ITranscodeService {

    @Inject
    private MediaServerConfig mediaServerConfig;

    private final Map<String, Transcode> TRANSCODE_MAP = new HashMap<>();

    @Override
    public R transcode(TranscodeParam param) {
        MK_MEDIA_SOURCE mkMediaSource = ZLM_API.mk_media_source_find2("rtmp", MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), 0);
        Assert.isNull(mkMediaSource, "当前流已在线");
        Assert.isFalse(TRANSCODE_MAP.containsKey(param.getStream()), "转码任务已存在");
        String pushUrl = StrUtil.format("rtmp://{}:{}/{}/{}", mediaServerConfig.getMediaIp(), mediaServerConfig.getRtmpPort(), param.getApp(), param.getStream());
        Transcode transcode = new Transcode(param, pushUrl);
        RunUtil.asyncAndTry(transcode::start);
        TRANSCODE_MAP.put(param.getStream(), transcode);

        return R.data(pushUrl);
    }

    @Override
    public void stopTranscode(String stream) {
        Transcode transcode = TRANSCODE_MAP.get(stream);
        if (transcode != null) {
            transcode.stop();
            TRANSCODE_MAP.remove(stream);
        }
    }


}
